package matching;

import java.util.ArrayList;
import parser.RTEXmlParser;
import data.RTENode;
import data.RTEPreprocessedData;
import data.RTESentence;

public class BLEUMatch extends Matcher {

	public BLEUMatch(String task, double threshold) {
		super(task, threshold);
	}

	@Override
	public void match() {
		numberOfTextCases = RTEPreprocessedData.rtePreprocessedDataList.size();

		//Iterate over each pair
		for (RTEPreprocessedData rteData : RTEPreprocessedData.rtePreprocessedDataList) {
			float precision = 0;
			boolean entails = false;
			float idfValue = 0;
			
			int matches = 0;
			int bigramMatches = 0;
			//iterate over n-grams from n=1 => 4
			for(int n = 1; n < 5; n++) {
				for (RTESentence hypSentence : rteData.getHypothesisSentences()) {
					ArrayList<RTENode> hypNodes = hypSentence.getNodes();
					for (RTESentence textSentence : rteData.getTextSentences()) {
						ArrayList<RTENode> textNodes = textSentence.getNodes();
						for(int i = 0; i <= textNodes.size() - n; i++) {
							for(int j = 0; j <= hypNodes.size() - n; j++) {
								if(compare(n, i, j, textNodes, hypNodes)) {
									matches++;
									idfValue += idfPreProcessed.get(hypNodes.get(j).getLemma());
									//set bigram values to nodes
									if(n == 2)
										bigramMatches++;
								}
							}
						}
					}
				}
			}
			
//			int numGrams = 4;
//			precision /= numGrams;
//			if(precision >= threshold) entails = true;
//	
			//calculate the total idf sum
			
			int totalHypSize = 0;					
			float idfHypSum = 0;
			for(RTESentence sentence : rteData.getHypothesisSentences()) {
				for (RTENode node : sentence.getNodes()) {
					idfHypSum += idfPreProcessed.get(node.getLemma());
				}
				totalHypSize += sentence.getNodes().size();
			}
			
			rteData.setBiGramMatchPercentage(bigramMatches / (float)totalHypSize);
			
			float idfWordMatch = idfValue / idfHypSum;
			if(idfWordMatch >= threshold) { 
				entails = true;
			}		
			
			this.addJudgement(rteData.getId(), entails);
		
			if(entails == rteData.isEntailment()) { 
				entailments++;
			}		
			else
				errors.add(rteData.getId());	
		}
		correctness = (float)entailments/(float)numberOfTextCases;

		System.out.println(this);
		RTEXmlParser.WritePredictions("BleuMatch", this.getJudgementData());
	}

	private boolean compare(int n, int textIndex, int hypIndex, ArrayList<RTENode> text, ArrayList<RTENode> hyp) {
		float matches = 0;
		
		for(int i = 0; i < n; i++) {
			if(text.get(i+textIndex).getLemma().equals(hyp.get(i+hypIndex).getLemma()) && 
			   !text.get(i+textIndex).getLemma().equals("")	&&
			   text.get(i+textIndex).getPosTag().equals(hyp.get(i+hypIndex).getPosTag()))
				matches++;
		}
		return matches == n;
	}
}